package com.industry.staff.controller.vo;

import com.industry.staff.dal.dataobject.Department;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@EqualsAndHashCode(callSuper = true)
@Data
public class DepartmentVo extends Department {

    public List<DepartmentVo> children;

    public static List<DepartmentVo> buildTree(List<Department> departments) {
        if(CollectionUtils.isEmpty(departments)){
            return new ArrayList<>();
        }
        Map<String, DepartmentVo> collect = buildMap(departments);
        List<DepartmentVo> roots = new ArrayList<>();
        collect.values().forEach(node -> {
            String pId = node.getPId();
            if (pId == null || pId.isEmpty() || !collect.containsKey(pId)) {
                // 没有父节点或父节点不存在，作为根节点
                roots.add(node);
            } else {
                // 找到父节点并添加到其 children 列表
                DepartmentVo parent = collect.get(pId);
                parent.getChildren().add(node);
            }
        });
        return roots;
    }


    public static Map<String,DepartmentVo> buildMap(List<Department> departments){
        return departments.stream().map(i -> {
            DepartmentVo treeNode = new DepartmentVo();
            BeanUtils.copyProperties(i, treeNode);
            treeNode.setChildren(new ArrayList<>());
            return treeNode;
        }).collect(Collectors.toMap(Department::getId, treeNode -> treeNode
        ));
    }

    //DFS count 深度优先递归子节点的数量  (先用static 写再说)
    public static Integer calChildrenCountDFS(DepartmentVo source){
        int count = source.getChildren().size();
        for (DepartmentVo child : source.getChildren()) {
            count += calChildrenCountDFS(child);
        }
        return count;
    }

    //DFS count 深度优先递归子节点的数量  (先用static 写再说)
    public static DepartmentVo calChildrenCountDFS(List<DepartmentVo> roots , String targetId){
        if (CollectionUtils.isEmpty(roots)) {
            return null;
        }
        for (DepartmentVo root : roots) {
            if(StringUtils.equals(targetId,root.getId())){
                return root;
            }
            DepartmentVo foundInChildren = calChildrenCountDFS(root.getChildren(), targetId);
            if (foundInChildren != null) {
                return foundInChildren;
            }
        }
        return null;
    }
}
